package com.cn.codebrush.字符串;

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * @Author Boolean
 * @Date 2022/5/23 10:56
 * @Version 1.0
 */
public class No20有效的括号 {
    public static void main(String[] args) {
        String s = "()[]{}";
        System.out.println(isValid(s));
    }


    /**
     * 解法二  使用栈
     * @param s
     * @return
     */
    public static boolean isValid2(String s) {
        int len = s.length();
        if(len%2 != 0){
            return false;
        }
        Map<Character,Character> map = new HashMap<Character,Character>(){{
            put(')','(');
            put(']','[');
            put('}','{');
        }};

        Deque<Character> deque = new LinkedList<>();
        for(int i=0;i<len;i++){
            char ch = s.charAt(i);
            if(map.containsKey(ch)){
                if(deque.isEmpty() || deque.peek() != map.get(ch)){
                    return false;
                }
                deque.pop();
            }else {
                deque.push(ch);
            }

        }


        return deque.isEmpty();
    }

    /**
     * 解法一  字符串替换
     * @param s
     * @return
     */
    public static boolean isValid(String s) {
        int len = s.length();
        for(int i=0;i<len;i++){
            s = s.replace("()","").replace("[]","").replace("{}","");
        }
        return s.length() == 0;
    }
}
